'use strict';
import React from "react";
import {View, StyleSheet} from "react-native";
import Container from "../../component/common/Container";
import NavigationBar from "../../component/navigation/NavigationBar";
import ListView from "../../component/list/ListView";
import LatestSubjectComponent from "../../component/find/LatestSubjectComponent";

class LatestSubjects extends React.PureComponent {

    constructor(props) {
        super(props);
        this.state = {data: []};
        this.page = 1;
        this.limit = 10;
    }

    componentDidMount() {
        this.requestDataSource();
    }

    requestDataSource = async () => {
        const data = {
            page: this.page,
            limit: this.limit
        };
        const result = await Services.post(ServicesApi.FIND_SUBJECT, data);
        // console.log('最新专题返回--------->', result);
        if (result.code === StatusCode.SUCCESS_CODE) {
            let dataSource = [];
            if (Array.isArray(result.data)) {
                if (data.page === 1) {
                    dataSource = result.data;
                } else {
                    let temp = this.state.data;
                    dataSource = temp.concat(result.data);
                }
            }
            this.setState({data: dataSource})
        }

        this._listRef && this._listRef.stopRefresh();
        this._listRef && this._listRef.stopEndReached({allLoad: result.data.length < this.limit}); // 是否加载完毕需要自行判断
    };

    _renderItem = (info) => {
        const {item, index} = info;
        return (
            <LatestSubjectComponent
                item={item}
                index={index}
            />

        )
    };

    _onRefresh = () => {
        this.page = 1;
        this.requestDataSource();
    };

    _onEndReached = () => {
        this.page++;
        this.requestDataSource();
    };

    _captureRef = (v) => {
        this._listRef = v
    };

    _keyExtractor = (item, index) => {
        return `${index}`
    };

    render() {
        const {params} = this.props.navigation.state;
        const pageTitle = params.pageTitle || '最新专题';
        return (
            <Container>
                <NavigationBar
                    title={pageTitle}
                />
                <ListView
                    data={this.state.data}
                    initialRefresh={false}
                    enableRefresh={true}
                    enableLoadMore={true}
                    ref={this._captureRef}
                    style={styles.listView}
                    onRefresh={this._onRefresh}
                    renderItem={this._renderItem}
                    keyExtractor={this._keyExtractor}
                    onEndReached={this._onEndReached}
                />
            </Container>
        );
    }
}

const styles = StyleSheet.create({
    listView: {},
});

export default LatestSubjects